<template>
  <a-spin size="large" tip="提交中..." :spinning="loading">
    <div class="paper-container">
      <title-info-modal>
        <a-button type="warning" class="label" @click="Data.restoreVisible = 'YJ'">
          <retweet-outlined class="mr-1" /> 调阅原卷
        </a-button>
        <a-button type="primary" class="label" @click="Data.restoreVisible = 'DTK'">
          <retweet-outlined class="mr-1" /> 调阅答题卡
        </a-button>
        <a-button type="success" class="label" @click="openModel('ckdUvisible')">
          <eye-outlined class="mr-1" /> 查看答案
        </a-button>
        <a-button
          type="danger"
          v-if="!questionsInfo?.pyZycIdList"
          @click="openModel('abnormalVisible')"
        >
          <exclamation-circle-outlined class="mr-1" /> 标记异常
        </a-button>
      </title-info-modal>
      <div class="main">
        <canvas-container
          :prpopsStyle="{
            width: '80%',
            height: '100%',
          }"
          :imgList="currentTopic.dtkqtxxVoList || []"
          :tagsList="tagsList || []"
          ref="canvasRef"
          :hasEventDblclick="true"
          :currentTopic="currentTopic"
          :countList="countList"
          :dfdSelected="dfdSelected"
          :questionsInfo="questionsInfo"
          :recordClick="recordClick"
          :contextmenuValue="Data.contextmenuValue"
          :showTipBool="Data.showTipValue"
          @closeTip="closeTip"
          @menuClick="menuClick"
          :menuList="menuList"
          :lfYcList="Data.lfYcList"
          @upAbnor="openModel('abnormalVisible')"
          @nextTopic="nextTopic"
          @panelStatus="panelStatus"
        >
          <template #tool>
            <div class="line"></div>
            <span class="tool-icon" @click="revokeScoring">
              <EnterOutlined />
              <span class="text">撤销评分</span>
            </span>
          </template>
        </canvas-container>

        <div class="mark-content">
          <QuizQues ref="quizQueRef" :disabledSubmitButton="panelStatu" :lfYcList="Data.lfYcList">
            <template #titleButton>
              <a-checkbox
                v-model:checked="Data.contextmenuheckboxValue"
                @change="setUserContextmenuValue"
              >
                右键开启评阅面板
              </a-checkbox>
            </template>
          </QuizQues>
        </div>
      </div>
    </div>

    <!--试卷答案 -->
    <answer-modal :currentTopic="currentTopic" v-model:ckd-uvisible="Data.ckdUvisible" />

    <!-- 答题卡还原 -->
    <restore-card
      v-model:restoreVisible="Data.restoreVisible"
      :pyZycId="questionsInfo.pyZycId || questionsInfo.pyZycIdList[0]"
      :kmdm="(route.query?.kmdm as string)"
    />

    <!-- 退出评阅 -->
    <sele-option-topic
      v-model:seleopti-bloon="Data.seleoptiBloon"
      :seleOptions="Data.seleOptions"
      :seleOptiTitle="Data.seleOptiTitle"
    />
    <!-- 标记异常弹窗 -->
    <abnormal-modal
      v-model:abnormal-visible="Data.abnormalVisible"
      :questionsInfo="{
        ...questionsInfo,
        kmdm: route.query.kmdm,
      }"
      :ycSource="questionsInfo.value?.pyZycIdList ? 'CP' : undefined"
      :pyKssj="startTime"
      :pyTjsj="dayjs().format('YYYY-MM-DD HH:mm:ss')"
    />
  </a-spin>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch, reactive } from 'vue'
import { Persistent } from '/@/utils/cache/persistent'

import dayjs from 'dayjs'

import titleInfoModal from './components/titleInfo.vue'
import abnormalModal from './components/abnormal.vue'
import seleOptionTopic from './components/seleOptionTopic.vue'
import answerModal from '/@/views/teacher/review/components/answer.vue'
import CanvasContainer from '/@/layouts/components/CanvasChart/canvasContainer.vue'
import QuizQues from './quizQues.vue'
import RestoreCard from './restoreCard.vue'
import { getDictionaryList } from '/@/views/teacher/home/index'

import {
  getExtractZycZgt,
  getZycwatchPaperCheck,
  getCpDataByAccount,
  myReviewWork,
} from '/@/api/teacher'
import { showPaper } from '/@/api/organization/examinationPaper'

import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage } = useMessage()

import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

import { useTeacherMarkStore } from '/@/store/modules/teacherMark'
const teacherMarkStore = useTeacherMarkStore()
const questionsInfo = computed(() => teacherMarkStore.getQuestions)
const currentTopic = computed(() => teacherMarkStore.getCurrentTopic ?? {}) // 评阅明细
const tagsList = computed(() => teacherMarkStore.getTagsList) // 当前打分列表
const countList = computed(() => teacherMarkStore.getCountList) // 当前题目得分分片列表
const dfdSelected = computed(() => teacherMarkStore.getDfdSelected ?? {}) //选中的得分点
const isNext = computed(() => teacherMarkStore.getNext) //是否评阅下一题
const loading = computed(() => teacherMarkStore.getLoading) //是否加载中

const canvasRef = ref() // 画布实例

import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const startTime: any = computed(() => userStore.getStartTime)
const addSubjectForm = computed(() => userStore.getSysConfig)

// 是否需要点击图片
const recordClick = computed(() => {
  if (!questionsInfo.value.pyZycIdList && addSubjectForm.value.clickDtkqtCheck4ZgtFlag) return true
  return false
})
// 页面数据
const Data = reactive({
  seleoptiBloon: false,
  abnormalVisible: false,
  ckdUvisible: false,
  restoreVisible: '',

  seleOptiTitle: '',
  seleOptions: [],

  contextmenuValue: 'menu',
  contextmenuheckboxValue: false,
  showTipValue: true,

  lfYcList: [],
} as any)

/**右键菜单事件 */
function menuClick(key) {
  switch (key) {
    case '1':
      // 打分面板
      canvasRef.value.showPanel()
      break
    case '2':
      // 调阅全卷
      Data.restoreVisible = 'YJ'
      break
    case '3':
      // 调阅答题卡
      Data.restoreVisible = 'DTK'
      break
    case '4':
      // 查看答案
      openModel('ckdUvisible')
      break
    case '5':
      // 标记异常
      openModel('abnormalVisible')
      break
    case '6':
      // 撤销打分
      revokeScoring()
      break
    default:
      break
  }
}

// 返回上一页
const pageGoBack = () => {
  router.back()
}

//开启弹窗事件
function openModel(e) {
  Data[e] = true
}

// 撤销打分
const revokeScoring = async () => {
  if (teacherMarkStore.setTagsList('pop', {})) {
    createMessage.success('撤销成功')
  } else createMessage.error('已经没有可撤销的评分记录了')
}

// 抽题
const getPageExtractZyc = async () => {
  let { code, data, message } = await getExtractZycZgt({
    stId: questionsInfo.value.stId,
    kmdm: route.query.kmdm,
  })
  if (code == 200) {
    teacherMarkStore.setQuestions(data)
    // 抽题成功 获取试题数据
    await getPageInfoFun()
  } else if (code == 8104 || code == 8103) {
    // 当前题型已经没有试题了
    teacherMarkStore.setLoading(false)
    getOtherQuestionTyp(message)
    return
  } else {
    createMessage.error(message)
    // 抽题失败 回到首页
    pageGoBack()
  }
}

// 获取重评题列表
const getTodoDaYcXxE = async () => {
  let { code, data } = await getCpDataByAccount({
    kmdm: route.query.kmdm,
  })
  if (code == 200 && data?.length) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].stId == questionsInfo.value.stId) {
        teacherMarkStore.setQuestions(data[i])
        return getPageInfoFun()
      }
    }
    getOtherQuestionTyp('当前题型重评题已完成')
  } else {
    getOtherQuestionTyp('重评题已完成')
  }
}

// 当前题型没有试题操作
const getOtherQuestionTyp = async e => {
  let { code, data } = await myReviewWork({}).catch(() => {
    createMessage.success(e)
    // 抽题失败 回到首页
    pageGoBack()
  })
  if ((code == 200 && data && data.length) || e === '当前题型重评题已完成') {
    Data.seleOptions = data
    openModel('seleoptiBloon')
    // message 无可评阅资源；
    Data.seleOptiTitle = e
  } else {
    createMessage.success(e)
    // 抽题失败 回到首页
    pageGoBack()
  }
}

// 获取图片列表
const getIMgLis = async () => {
  const { data, code } = await showPaper({
    pyZycId: questionsInfo.value.pyZycId || questionsInfo.value.pyZycIdList[0],
  })
  if (code == 200) {
    currentTopic.value.dtkqtxxVoList = data
  }
  if (!data.length) {
    createMessage.error('当前试卷没有获取到图片')
  }
}

// 获取页面信息（图片，试题数据）
async function getPageInfoFun() {
  teacherMarkStore.setLoading(true)
  teacherMarkStore.setDfdSelected({}) //清空得分点
  try {
    let { code, data, message } = await getZycwatchPaperCheck({
      pyZycId: questionsInfo.value.pyZycId || questionsInfo.value.pyZycIdList[0],
      kmdm: route.query.kmdm,
      stId: questionsInfo.value.stId,
    })
    if (code == 200) {
      if (data.dfdInfoList?.length) {
        data.dfdInfoList.sort((a, b) => a.sortNum - b.sortNum)
      }
      teacherMarkStore.setCurrentTopic(data)
      if (!data.dtkqtxxVoList?.length) {
        getIMgLis()
      }
      userStore.setStartTime(dayjs().format('YYYY-MM-DD HH:mm:ss'))
    } else {
      createMessage.error(message)
    }
  } catch (error) {
    createMessage.error('题目数据获取失败，请稍后重试！')
  } finally {
    teacherMarkStore.setLoading(false)
  }
}

// 获取下一张试卷
watch(
  () => isNext.value,
  async val => {
    teacherMarkStore.setTagsList('', {})
    if (val) {
      teacherMarkStore.setLoading(true)
      // 清空打分记录 试卷复位
      canvasRef.value.restoration()
      if (questionsInfo.value.pyZycIdList) {
        //重评题
        getTodoDaYcXxE()
      } else {
        // 上次未完成的抽题 // 重新抽题
        await getPageExtractZyc()
      }
      teacherMarkStore.setNext(false)
    }
  },
  {
    immediate: true,
  }
)

onMounted(async () => {
  if (questionsInfo.value.pyZycIdList) {
    menuList.value = menuList.value.filter(e => e.key != '5')
    //重评题
    getTodoDaYcXxE()
  } else {
    // 上次未完成的抽题 // 重新抽题
    await getPageExtractZyc()
  }
  let constextmenuObj: any = Persistent.getLocal('contextmenuValue') || {}
  if (userStore.getUserInfo.account && constextmenuObj[userStore.getUserInfo.account]) {
    Data.contextmenuValue = constextmenuObj[userStore.getUserInfo.account]
    Data.contextmenuheckboxValue =
      constextmenuObj[userStore.getUserInfo.account] == 'panel' ? true : false
  } else {
    setUserContextmenuValue()
  }

  Data.showTipValue = setUserShowTipValue()

  Data.lfYcList = await getDictionaryList('lfCode')
})

function setUserContextmenuValue() {
  Data.contextmenuValue = Data.contextmenuheckboxValue ? 'panel' : 'menu'
  if (!userStore.getUserInfo.account) return
  let constextmenuObj: any = Persistent.getLocal('contextmenuValue') || {}
  Persistent.setLocal('contextmenuValue', {
    ...constextmenuObj,
    [userStore.getUserInfo.account]: Data.contextmenuValue,
  })
}

function closeTip(e) {
  Data.showTipValue = false
  if (e) {
    setUserShowTipValue(true)
  }
}

function setUserShowTipValue(e: boolean = false) {
  if (!userStore.getUserInfo.account) return true
  let showTipObj: any = Persistent.getLocal('showTipValue') || {}
  if (e) {
    Persistent.setLocal('showTipValue', {
      ...showTipObj,
      [userStore.getUserInfo.account]: true,
    })
  }
  if (showTipObj[userStore.getUserInfo.account]) return false
  return true
}

const menuList = ref([
  { key: '1', name: '评分' },
  { key: '2', name: '调阅原卷' },
  { key: '3', name: '调阅答题卡' },
  { key: '4', name: '查看答案' },
  { key: '5', name: '标记异常' },
  { key: '6', name: '撤销评分' },
])

const quizQueRef = ref()
/**
 *
 * @param val 异常信息对象
 * @param e 是否提交并下一题
 */
function nextTopic(val: any = {}, e: boolean = false) {
  quizQueRef.value.outUpSubmit(val, e)
}

/**
 * 禁用提交
 */
const panelStatu = ref(false)
function panelStatus(e: boolean) {
  panelStatu.value = e
}
</script>

<style lang="less" scoped>
.paper-container {
  height: calc(100vh - @multiple-height);
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .label {
    cursor: pointer;
    margin-right: 16px;
    margin-left: 5px;
    font-weight: 700;
  }

  .line {
    height: 20%;
    width: 1px;
    margin: 0 20px;
    background: #dddada;
  }

  .tool-icon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }

  .main {
    height: calc(100vh - 80px);
    display: flex;
    .mark-content {
      flex: 1;
      background-color: #fff;
      height: 100%;
    }
  }
}
</style>
